﻿/// <reference path="/Js/jsUtil.js"/> 
/// <reference path="/Js/main.js"/> 
/// <reference path="/Js/ext-5.0.0-gpl/build/ext-all.js"/> 
/// <reference path="/Js/app.js"/> 
/**
* 
*/
Ext.require('Region.Js.Region_Module');
Ext.define("CRM.Js.Select_Buyers", {
    $win: {},
    isSingleSelect: false,
    SelectedArray: [],
    Grid: {},
    show: function (CustomerId) {
        var _callbackid = arg0; //返回到那个id里去
        this.isSingleSelect = (arg1 == "true");
        var param = { CustomerId: 0 };
        var _module = this;
        var winDom;
        var win = Ext.create('Ext.window.Window', {
            title: '选择购房客户', height: 560, width: 700, modal: true,
            loader: {
                url: '/CRM/Templates/Select_Buyers.htm', autoLoad: true, scripts: true,
                listeners: {
                    load: function (obj, eOpts) {
                        winDom = $("#" + obj.target.id);
                        _module.$win = winDom;
                        renderUserControls(winDom);
                        _module.renderList(Ext.get(winDom.find('.divMainList')[0]));
                    }
                }
            },
            buttons: [
            {
                text: "确认",
                handler: function () {
                    var _win = this.up('window');
                    console.log('callback', _callbackid);
                    $("#" + _callbackid).val($("input[name=SelectedNames]", _win.dom).val());
                    $("#" + _callbackid).next().val($("input[name=SelectedIds]", _win.dom).val()).change();
                    _win.close();
                }
            }, {
                text: "关闭",
                handler: function () {
                    this.up("window").close();
                }
            }],
            listeners: {
                close: function () {
                }
            }
        }).show();
    },
    renderList: function (view) {
        var _module = this;
        var Store = Ext.create('Ext.data.Store', { //store和model一起创建
            fields: ['CustomerId'],
            pageSize: 30,
            autoLoad: true,
            proxy: {
                type: 'ajax',
                enablePaging: true,//支持翻页
                url: '/CRM/Services/CRM_Buyers.asmx/GetLists',
                pageParam: 'page',
                startParam: '{startParam}',
                limitParam: 'rows',
                headers: { "Content-Type": 'application/json' },
                reader: {
                    type: 'json',
                    rootProperty: 'd.Table.rows',
                    totalProperty: 'd.Total'
                },
                writer: {
                    type: 'json'
                },
                extraParams: $.par2Json($("form[name=fmCRM_Buyers_Select]", _module.dom).serialize()),
                sortParam: 'LastTime'
            }
        });
        var Columns = easyui2extgrid([[
                    { field: 'CustomerId', title: '编号', width: 40 },
                    { field: 'CustomerName', title: '姓名', width: 50, align: 'center' },
                    { field: 'Sex', title: '性别', width: 30, align: 'center', formatter: function (c) { return X_CRM_SEX[c]; } },
                    { field: 'Residence', title: '户籍', width: 100, align: 'center' },
                    { field: 'Tel', title: '电话', align: 'center' },
                    { field: 'AddUser', title: '录入人', align: 'center' },
                    { field: 'AddTime', title: '录入时间', align: 'center', formatter: function (c) { return formatDate(c); } }
        ]]);
        var tbl = view.query(".mainList");
        var searchHeight = $(".auto", view.dom).height();
        if (!searchHeight) searchHeight = 0;
        var sm = new Ext.selection.CheckboxModel({ checkOnly: false, mode: this.isSingleSelect ? "SINGLE" : 'SIMPLE' });
        var grid = Ext.create('Ext.grid.Panel', {
            scroll: true, height: deskExt.getHeight() - searchHeight - X_TAB_HEIGHT,
            store: Store, width: '100%', forceFit: true, selModel: sm,
            columns: Columns,
            listeners: {
                cellclick: function (cell, td, cellIndex, record, tr, rowIndex, e, eopts) {
                    if (cellIndex > 0) {
                        var Sells_View = Ext.create("CRM.Js.Buyers_View");
                        Sells_View.show(record.data.CustomerId);
                    }

                },
                select: function (t, record, index, eOpts) {
                    if (!record.data) return;
                    var position = _module.SelectedArray.indexOf(record.data);
                    var isExists = false;
                    for (var j = 0; j < _module.SelectedArray.length; j++) {
                        if (_module.SelectedArray[j].CustomerId == record.data.CustomerId) {
                            isExists = true;
                            break;
                        }
                    }
                    if (!isExists) { 
                        _module.SelectedArray = [];+4 
                        _module.SelectedArray.push(record.data);
                        renderResult();
                    }
                },
                deselect: function (t, record, index, eOpts) {
                    var _resultArray = [];
                    $.map(_module.SelectedArray, function (item) {
                        if (item.SellId == record.data.SellId) { }
                        else {
                            _resultArray.push(item);
                        }
                    });
                    _module.SelectedArray = _resultArray;
                    renderResult();
                }
            },
            bbar: Ext.create('Ext.PagingToolbar', {
                store: Store,
                displayInfo: true,
                displayMsg: '显示 {0} - {1} 条，共计 {2} 条',
                emptyMsg: "没有数据"
            }),
            renderTo: tbl
        });
        this.Grid = grid;
        if (this.SelectedArray) { renderResult();}
        function renderResult() {
            var _ids = "", _names = "";
            $.map(_module.SelectedArray, function (item, k) {
                if (_ids != "") _ids += ",";
                if (_names != "") _names += ",";
                _ids += item.CustomerId;
                _names += item.CustomerName;
            });
            $("input[name=SelectedIds]", _module.dom).val(_ids);
            $("input[name=SelectedNames]", _module.dom).val(_names);
        }
        //events
        $("form[name=fmCRM_Buyers_Select]", _module.dom).submit(function () {
            grid.store.proxy.extraParams = $.par2Json($("form[name=fmCRM_Buyers_Select]", _module.dom).serialize());
            grid.store.reload();
            return false;
        });
    },
    constructor: function (config) {
        this.initConfig(config);
    }
});
